package com.baidu.iit.pxp.el.resolver;

import com.baidu.iit.pvm.delegate.VariableScope;
import com.baidu.iit.pxp.el.ELContext;
import com.baidu.iit.pxp.entity.ExecutionEntity;
import com.baidu.iit.pxp.entity.TaskEntity;

import java.beans.FeatureDescriptor;
import java.util.Iterator;

/**
 * User: huangweili
 * Date: 14-4-29
 * Time: 下午1:49
 */
public class VariableScopeElResolver extends ELResolver {

    public static final String EXECUTION_KEY = "execution";
    public static final String TASK_KEY = "task";
    protected VariableScope variableScope;

    public VariableScopeElResolver(VariableScope variableScope) {
        this.variableScope = variableScope;
    }

    public Object getValue(ELContext context, Object base, Object property) {

        if (base == null) {
            String variable = (String) property;

            if ((EXECUTION_KEY.equals(property) && variableScope instanceof ExecutionEntity)
                    || (TASK_KEY.equals(property) && variableScope instanceof TaskEntity)) {
                context.setPropertyResolved(true);
                return variableScope;
            } else if (EXECUTION_KEY.equals(property) && variableScope instanceof TaskEntity) {
                context.setPropertyResolved(true);
                return ((TaskEntity) variableScope).getExecution();
            } else {
                if (variableScope.hasVariable(variable)) {
                    context.setPropertyResolved(true);
                    return variableScope.getVariable(variable);
                }
            }
        }


        return null;
    }

    public boolean isReadOnly(ELContext context, Object base, Object property) {
        if (base == null) {
            String variable = (String) property;
            return !variableScope.hasVariable(variable);
        }
        return true;
    }

    public void setValue(ELContext context, Object base, Object property, Object value) {
        if (base == null) {
            String variable = (String) property;
            if (variableScope.hasVariable(variable)) {
                variableScope.setVariable(variable, value);
            }
        }
    }

    public Class<?> getCommonPropertyType(ELContext arg0, Object arg1) {
        return Object.class;
    }

    public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext arg0, Object arg1) {
        return null;
    }

    public Class<?> getType(ELContext arg0, Object arg1, Object arg2) {
        return Object.class;
    }

}
